/**
 * angular路由route和控制器controller配置
 */

var mainApp = angular.module("mainApp", [ 'ngRoute' ]);

var user = null; // 自定义全局变量。用来存放登录后的返回信息。
var guid = null; // 全局变量，用来存放当前设备id。
var target = null;//全局变量，存放调用监控画面设备的哈希值

mainApp.config([ '$routeProvider', function($routeProvider) {
	$routeProvider.when('/homePage', {
		templateUrl : 'page/home/homePage.html',
		controller : 'contentController',
		cache : false
	}).when('/time', {
		templateUrl : 'page/home/time.html',
		controller : 'timeController',
		cache : false
	}).when('/monitor', {
		templateUrl : 'page/home/monitor.html',
		cache : false
	}).when('/alarm', {
		templateUrl : 'page/notice/alarm.html',
		controller : 'alarmController',
		cache : false
	}).when('/equipmentsInfo', {
		templateUrl : 'page/home/equipmentsInfo.html',
		controller:'equipmentController',
		cache : false
	}).when('/notice', {
		templateUrl : 'page/notice/notice.html',
		controller : "noticeController",
		cache : false
	}).when('/rule', {
		templateUrl : 'page/notice/rule.html',
		controller : 'equipmentsController',
		cache : false
	}).when('/about', {
		templateUrl : 'page/setting/about.html',
		cache : false
	}).when('/login', {
		templateUrl : 'page/setting/login.html',
		controller : 'loginController',
		cache : false
	}).when('/register', {
		templateUrl : 'page/setting/register.html',
		controller : 'registerController',
		cache : false
	}).when('/equipment', {
		templateUrl : 'page/setting/equipment.html',
		controller : 'equipmentController',
		cache : false
	}).when('/webRtc', {
		templateUrl : 'page/video/webRtc.html',
		controller : 'webRtcController',
		cache : false
	}).when('/registerEquipment', {
		templateUrl : 'page/setting/registerEquipment.html',
		controller : 'equipmentController',
		cache : false
	}).when('/equipmentInformation', {
		templateUrl : 'page/setting/equipmentInformation.html',
		controller : 'curEquipmentController',
		cache : false
	}).when('/setting', {
		templateUrl : 'page/setting/setting.html',
		controller : 'loginStateController',
		cache : false
	}).when('/accountInformation', {
		templateUrl : 'page/setting/accountInformation.html',
		controller : 'accountInformationController'
	}).when('/fillUserInfo', {
		templateUrl : 'page/setting/fillUserInfo.html',
		controller : 'fillUserInfoController'
	}).when('/changePassword', {
		templateUrl : 'page/setting/changePassword.html',
		controller : 'accountInformationController'
	}).when('/privacyPolicy', {
		templateUrl : 'page/setting/privacyPolicy.html'
	}).when('/aboutUs', {
		templateUrl : 'page/setting/aboutUs.html'
	}).when('/videoSetting', {
		templateUrl : 'page/setting/videoSetting.html',
		cache : false
	}).when('/videoSupport', {
		templateUrl : 'page/setting/videoSupport.html',
		cache : false
	}).when('/video', {
		templateUrl : 'page/video/video.html',
		controller : 'videoController',
		cache : false
	}).when('/welcomePage', {
		templateUrl : 'page/welcome.html',
		cache : false
	}).otherwise({
		redirectTo : '/homePage'
	});
} ]);
/* global $http.post config */
mainApp
		.config(function($httpProvider) {
			$httpProvider.defaults.transformRequest = function(data) {
				if (data === undefined) {
					return data;
				}
				return $.param(data);
			};
			$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
		});

function checkApp() {
	var apps = new Array();
	apps.push({
		"appName" : "camera",
		"checked" : true,
		"description" : "日了够了"
	});
	apps.push({
		"appName" : "accelerometer",
		"checked" : true,
		"description" : "dsaddasdd"
	});
	apps.push({
		"appName" : "camera3",
		"checked" : false,
		"description" : "dasda"
	});
	return apps;
}


mainApp.controller("noticeController", function($scope, $http) {

	// 获取用户信息
	$http.get("getUserInfo.action").success(function(response) {
		if (response.result == "success") {
			$scope.userInfo = response.userInfo;
		} else {
			// console.log(response.reason); //如果在此处弹出窗口的话，会影响后面的代码无法正常执行
		}
	});

});


mainApp.controller('ruleSetController', function($scope, $http) {
	// 从服务端获取当前用户的设备列表
	$http.post("getAllDeviceList.action").success(function(response) {
		var equipments = new Array();
		var deviceList = response.deviceList;
		for ( var i = 0; i < deviceList.length; i++) {
			equipments.push({
				"username" : deviceList[i].username,
				"deviceName" : deviceList[i].deviceName,
				"deviceHash" : deviceList[i].deviceHash
			});
		}
		$scope.equipments = equipments;
	});
	// 获取当前设备
	$scope.curEquipment = {
		"name" : "",
		"number" : guid
	};
	// 从服务器端获取当前设备的信息（如果还没注册的话是获取不到的）
	var temp_url = "getDeviceInfo.action?device.deviceHash="
			+ $scope.curEquipment.number;
	$http.get(temp_url).success(function(response) {
		if (response.result == "success") {
			$scope.curEquipment.name = response.device.deviceName;
		} else {
			// console.log(response.reason);
		}
	});

	// add rule
	// 前段设置
	$scope.newRule = {
		"deviceHash" : "hash1",
		"eventType" : 2,
		"nextDeviceHash" : "hash2",
		"nextEventType" : 3
	};
	
	$scope.addRule = function() {
		$.post("addRule.action", {
			"de.deviceHash" : $scope.newRule.deviceHash,
			"de.eventType" : $scope.newRule.eventType,
			"de.nextDeviceHash" : $scope.newRule.nextDeviceHash,
			"de.nextEventType" : $scope.newRule.nextEventType
		}, function(response) {
			switch (response.result) {
			case "success":
				console.log("事件添加成功");
				break;
			case "error":
				console.log(response.reason);
				break;
			}
		}, "json");
	};

});

// 判断登陆状态，来显示登入/登出
mainApp.controller('loginStateController', function($scope) {
	if (!getCookie("user")) {
		$scope.loginState = "登入";
	} else {
		$scope.loginState = "登出";
	}
	var loginState = document.getElementById("loginState");
	if ($scope.loginState == "登入") {
		loginState.href = "#login";
	} else {
		loginState.onclick = logout;
		// loginState.href = "#";
	}
});

function logout($location) {
	// 设置重名cookie，并设置过期时间，删除cookie
	var date = new Date();
	date.setTime(date.getTime() - 10000);
	document.cookie = "user=a; expires=" + date.toGMTString();
	$.get("logout.action", function() {
	});
}
mainApp.controller('contentController', function($scope) {
	/* localStorage.removeItem("Welcome"); */
	if (websocket == null && guid!= null) {
		websocket_init(guid);
	}
	
	$scope.isOpen=true;
	$scope.changeOpen = function() {
		$scope.isOpen=!$scope.isOpen;
		$.post("changeMonitor.action", {
			"monitor" : $scope.isOpen
		}, function(response) {
			switch (response.result) {
			case "success":
				console.log("事件添加成功");
				break;
			case "error":
				console.log(response.reason);
				break;
			}
		}, "json");
	}
	$scope.welcomePageLoaded = function() {
		try {
			var welcome = window.localStorage.getItem("Welcome");
			if (welcome == null) {
				window.location.href = "page/welcome.html";
			}
		} catch (e) {
			showAlert("设备不支持localStorage!");// debug
		}
	};
	$scope.welcomePageLoaded();
	$scope.apps = checkApp();
	$scope.openApp = function(appName) {
		switch (appName) {
		case "camera":
			console.log("1");
			self.location = "page/camera.html";
			break;
		case "accelerometer":
			console.log("2");
			self.location = "page/accelerometer.html";
			break;
		}
	};
});

mainApp.controller('timeController',function($scope){
/*	$('#datetimepicker1').datetimepicker({
		inline:true
	});
	$('#datetimepicker2').datetimepicker({
		inline:true
	});*/
});
mainApp.controller('alarmController',function($scope,$http){
	
	$scope.receiveAlarm = function(){
		$.post("receiveAlarm.action", {
			
		}, function(response) {
			switch (response.result) {
			case "success":
				// 跳到查看监控页面
				// TODO
				self.location("/");
				break;
			case "error":
				console.log(response.reason);
				break;
			}
		}, "json");
	};
	
});

mainApp.controller('webRtcController',function($scope){
	
	console.log("con is null");
	$scope.con = null;
	
});

mainApp.controller('videoController', function($scope, $http) {
	$scope.index=0;
	$scope.videos=[{id:"1",src:"sound/150819-1328.webm"},{id:"2",src:"sound/150819-1402.webm"}];
  /*  $http.post("getAllVideoList.action").success(function(response){
		var videos = new Array();
		var videoList = response.videoList;
		
		for(var i=0;i<videos.length;i++){
			videos.push({
				"deviceHash":videoList[i].deviceHash,
				"deviceName":videoList[i].deviceName,
				"date":videoList[i].date,
				"src":videoList[i].src
			});
		}
		$scope.videos = videos;
	});*/

});

mainApp.controller('equipmentController',function($scope,$http){
	$http.post("getAllDeviceList.action").success(function(response){
		var equipments = new Array();
		var deviceList = response.deviceList;
		for(var i=0;i<deviceList.length;i++){
			if(deviceList[i].isOnline) deviceList[i].isOnline="在线";
			else deviceList[i].isOnline="不在线";
			equipments.push({
				"deviceName":deviceList[i].deviceName,
				"deviceHash":deviceList[i].deviceHash,
				"isOnline":deviceList[i].isOnline,
				"remaindPower":deviceList[i].remaindPower
			});
		}
		$scope.equipments = equipments;
	});
	
	$scope.selected=function(number){
		$.post("getDeviceInfo.action", {
			"device.deviceHash" : number
		}, function(response) {
			switch (response.result) {
			case "success":
				document.cookie = "guid=" +number;
				guid = getCookie("guid");
				console.log("guid : " + guid);
				websocket_init(guid);
				if (response.device.isKey == false) {
					startSensor();
				}
				self.location("/");
				break;
			case "error":
				console.log(response.reason);
				break;
			}
		}, "json");
	};
	
	// 注册设备
	$scope.isKey=true;
	$scope.confirm = function() {
		guid=$scope.curEquipment.number + "_" + user.username;
		console.log("test guid :" + guid);
		$.post("insertDevice.action", {
			"device.deviceHash" : guid,
			"device.deviceName" : $scope.curEquipment.name,
			"device.isKey" : $scope.isKey
		}, function(response) {
			switch (response.result) {
			case "success":
				console.log("注册设备成功");
				document.cookie = "guid=" +guid;
				websocket_init(guid);
				if (response.device.isKey == false) {
					startSensor();
				}
				self.location("/");
				break;
			case "error":
				console.log(response.reason);
				self.location = "#registerEquipment";
				break;
			}
		}, "json");
		
	};
	
	$scope.selWebRtc= function(number){
		console.log(number);
		target = number;
	};
});

mainApp.controller('curEquipmentController', function($scope, $http) {
	$scope.curEquipment = {
			"name" : "",
			"number" : guid
	};
	
	// 从服务器端获取当前设备的信息
	var temp_url = "getDeviceInfo.action?device.deviceHash="
			+guid;
	$http.get(temp_url).success(function(response) {
		if (response.result == "success") {
			$scope.curEquipment.name = response.device.deviceName;
		} else {
			 
		}
	});
	
	$scope.submitInfo = function() {
		$.post("updateDevice.action", {
			"device.deviceHash" : $scope.curEquipment.number,
			"device.deviceName" : $scope.curEquipment.name
		}, function(response) {
			switch (response.result) {
			case "success":
				console.log("修改设备信息成功");
				break;
			case "error":
				console.log(response.reason);
				break;
			}
		}, "json");
	};
	
});

/*mainApp.controller('equipmentsController', function($scope, $http) {
	// 从服务端获取当前用户的设备列表
	$http.post("getAllDeviceList.action").success(function(response) {
		var equipments = new Array();
		var deviceList = response.deviceList;
		for ( var i = 0; i < deviceList.length; i++) {
			equipments.push({
				"username" : deviceList[i].username,
				"deviceName" : deviceList[i].deviceName,
				"deviceHash" : deviceList[i].deviceHash
			});
		}
		$scope.equipments = equipments;
	});

	$scope.curEquipment = {
		"name" : "",
		"number" : getGuid()
	};

	// 从服务器端获取当前设备的信息（如果还没注册的话是获取不到的）
	var temp_url = "getDeviceInfo.action?device.deviceHash="
			+ $scope.curEquipment.number;
	$http.get(temp_url).success(function(response) {
		if (response.result == "success") {
			$scope.curEquipment.name = response.device.deviceName;
		} else {
			// console.log(response.reason);
		}
	});

	$scope.init = function() {
		$scope.curEquipment.number = getGuid();
	};
	$scope.confirm = function() {
		$.post("insertDevice.action", {
			"device.deviceHash" : $scope.curEquipment.number,
			"device.deviceName" : $scope.curEquipment.name
		}, function(response) {
			switch (response.result) {
			case "success":
				console.log("注册设备成功");
				break;
			case "error":
				console.log(response.reason);
				break;
			}
		}, "json");
	};

	// 修改设备信息
	$scope.submitInfo = function() {
		$.post("updateDevice.action", {
			"device.deviceHash" : $scope.curEquipment.number,
			"device.deviceName" : $scope.curEquipment.name
		}, function(response) {
			switch (response.result) {
			case "success":
				console.log("修改设备信息成功");
				break;
			case "error":
				console.log(response.reason);
				break;
			}
		}, "json");
	};

});*/

mainApp.controller("accountInformationController", function($scope, $http) {

	// 获取用户信息
	$http.get("getUserInfo.action").success(function(response) {
		if (response.result == "success") {
			var userInfo = response.userInfo;
			$scope.address = userInfo.address;
			$scope.firstContact = userInfo.firstContact;
			$scope.enmergencyContact = userInfo.enmergencyContact;
			$scope.contactEmail = userInfo.contactEmail;
		} else {
			// console.log(response.reason); //如果在此处弹出窗口的话，会影响后面的代码无法正常执行
		}
	});


	// 提交用户信息
	$scope.submitUserInfo = function() {
		$.post("updateUserInfo.action", {
			"userInfo.address" : $scope.address,
			"userInfo.firstContact" : $scope.firstContact,
			"userInfo.enmergencyContact" : $scope.enmergencyContact,
			"userInfo.contactEmail" : $scope.contactEmail
		}, function(response) {
			if (response.result == "success") {
				console.log("修改账号信息成功");
				console.log("test change");
				self.location = "#";
			} else {
				console.log(response.reason);
			}
		}, "json");
	}

	// 修改密码
	$scope.submitPassword = function() {
		if ($scope.newPassword == $scope.renewPassword) {
			$.post("changePassword.action", {
				"oldPassword" : $scope.oldPassword,
				"newPassword" : $scope.newPassword
			}, function(response) {
				if (response.result == "success") {
					console.log("修改密码成功");
					self.location = "#";
				} else {
					console.log(response.reason);
				}
			}, "json");
		} else {
			console.log("两次输入的新密码不一致");
		}
	}
});
/**
 * 提交用户
 */
mainApp.controller("fillUserInfoController", function($scope, $http) {
	$scope.submitUserInfo = function() {
		$.post("updateUserInfo.action", {
			"userInfo.address" : $scope.address,
			"userInfo.firstContact" : $scope.firstContact,
			"userInfo.enmergencyContact" : $scope.enmergencyContact,
			"userInfo.contactEmail" : $scope.contactEmail
		}, function(response) {
			if (response.result == "success") {
//				console.log("修改账号信息成功");
				self.location = "#equipment";
			} else {
				console.log(response.reason);
			}
		}, "json");
	}
});


mainApp.controller("loginController", function($scope, $http) {
	$scope.formData = {};
	$scope.login = function() {
		$.post("login.action", {
			"username" : $scope.username,
			"password" : $scope.password
		}, function(response) {
			switch (response.result) {
			case "success":
				user = eval("(" + response.user + ")");
				// 把全局变量存进cookie里面
				document.cookie = "user=" + user;
				document.cookie = "username=" +user.username;
				self.location = "#equipment";
				break;
			case "error":
				 // 提示失败信息。
				$scope.errorMsg=response.reason;
				break;
			}
		}, "json");
	};
});
mainApp.controller("registerController", function($scope) {
	$scope.register = function() {
		$.post("register.action", {
			"username" : $scope.username,
			"password" : $scope.password
		}, function(response) {
			switch (response.result) {
			case "success":
				
				user = eval("(" + response.user + ")");
				// 把全局变量存进cookie里面
				document.cookie = "user=" + user;
				document.cookie = "username=" +user.username;
				// 注册成功之后，跳转到填写信息页面
				self.location = "#fillUserInfo";
				break;
			case "error":
				console.log(response.reason); // 显示失败信息
				self.location = "#register";
				break;
			}
		}, "json");
	};
});

mainApp.controller("ruleController", function($scope) {
});
